package com.langsheng.lsintell.network;

import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.langsheng.lsintell.cmd.request.LSRequest;
import com.langsheng.lsintell.cmd.response.LSResponse;
import com.langsheng.lsintell.interfaces.LSResDataListener;
import com.langsheng.lsintell.interfaces.LSResponseListener;
import com.langsheng.lsintell.ui.widget.LSWaitingDialog;
import com.langsheng.lsintell.utils.LSUtil;

/**
 * Created by xuwei on 2017/3/17.
 */

public class LSNet {
    private static final LSNet ourInstance = new LSNet();

    public static LSNet getInstance() {
        return ourInstance;
    }

    private LSNet() {
    }

    private Context context;
    private LSWaitingDialog waitingDialog;
    private Handler handler;

    public void init(Context context) {
        this.context = context.getApplicationContext();
        waitingDialog = new LSWaitingDialog(this.context);
        handler = new Handler();
    }

    public void sendRequest(LSRequest request, final boolean isShowWaiting, final LSResDataListener listener) {
        if (isShowWaiting) {
            waitingDialog.show();
        }
        LSNetwork.getInstance().sendRequest(request, new LSResponseListener() {
            @Override
            public boolean onResponse(final LSResponse res) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        String content = res.getContent();
                        String errCode = parseErrCode(content);
                        if (TextUtils.isEmpty(errCode)) {
                            errCode = "1";
                        }
                        if (errCode.equalsIgnoreCase("0")) {
                            listener.onResponse(content);
                        } else {
                            LSUtil.showError(context, errCode);
                            listener.onResponseErr(errCode, content);
                        }
                        if (isShowWaiting) {
                            waitingDialog.dismiss();
                        }
                    }
                });
                return true;
            }
        });
    }

    private String parseErrCode(String json) {
        JSONObject object = JSONObject.parseObject(json);
        JSONObject headJson = object.getJSONObject("head");
        return headJson.getString("errcode");
    }
}
